﻿using Microsoft.VisualBasic.CompilerServices;
using Daemon.Infrustructure.EF;
using Daemon.Common.Helpers;
using Daemon.Repository.EF.Enums;
using Daemon.Model;
using Daemon.Repository.Contract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Daemon.Repository.EF
{
    public class AdminRoleRepository : Repository<AdminRole>, IAdminRoleRepository
    {
        protected override Expression<Func<AdminRole, int>> PrimaryKeyExpression => r => r.Id;

        public AdminRoleRepository(ApiDBContent context) : base(context)
        {
        }

        protected override IEnumerable<AdminRole> IncludeRelationships(IEnumerable<AdminRole> entities, ApiDBContent context)
        {
            SetUserInfo(entities);

            return entities;
        }

        private void SetUserInfo(IEnumerable<AdminRole> entities)
        {
            if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, AdminRoleRelationshipEnum.UserInfo))
            {
                return;
            }
            var addUserIds = entities.Select(r => r.AddUserId).ToList();
            var updateUserIds = entities.Select(r => r.UpdateUserId).ToList();
            var allUserIds = addUserIds.Concat(updateUserIds).ToList();
            var userDic = Context.AdminUser.Where(r => allUserIds.Contains(r.Id)).ToDictionary(r => r.Id, r => r);
            foreach (var entity in entities)
            {
                if (userDic.TryGetValue(entity.AddUserId, out AdminUser addUser))
                {
                    entity.AddUser = addUser;
                }

                if (userDic.TryGetValue(entity.UpdateUserId, out AdminUser updateUser))
                {
                    entity.UpdateUser = updateUser;
                }
            }
        }
    }
}
